<template>
    <div class="post-detail-container">
      <!-- 帖子详情 -->
      <div class="post-main">
        <h1 class="post-title">{{ postData.title }}</h1>
        <div class="post-meta">
          <el-avatar :src="postData.avatar" size="small" />
          <span class="author">{{ postData.author }}</span>
          <span class="publish-time">{{ formatTime(postData.createTime) }}</span>
          <el-tag type="info" size="small">
            {{ postData.viewCount }} 阅读
          </el-tag>
        </div>
        <div class="post-content" v-html="postData.content"></div>
        <div class="post-tags">
          <el-tag
            v-for="tag in postData.tags"
            :key="tag"
            type="info"
            size="small"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>

      <!-- 评论区 -->
      <div class="comment-section">
        <h3 class="comment-title">评论（{{ commentList.length }}）</h3>

        <!-- 评论输入 -->
        <div class="comment-input">
          <el-form :model="commentForm" :rules="commentRules" ref="commentFormRef">
            <el-form-item prop="content">
              <el-input
                type="textarea"
                :rows="3"
                v-model="commentForm.content"
                placeholder="写下你的评论..."
                maxlength="500"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-button
              type="primary"
              size="small"
              @click="submitComment"
            >
              发布评论
            </el-button>
          </el-form>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <div
            v-for="comment in commentList"
            :key="comment.id"
            :class="['comment-item', { 'child-comment': comment.parentId }]"
          >
            <el-avatar :src="proxy.globalInfo.imageUrl+comment.avatar" size="default" >
            </el-avatar>
            <div class="comment-content">
              <div class="comment-header">
                <span class="username">{{ comment.username }}</span>
                <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
              </div>
              <div class="comment-text">{{ comment.content }}</div>

              <!-- 嵌套回复 -->
              <div
                v-if="comment.replies && comment.replies.length"
                class="reply-list"
              >
                <div
                  v-for="reply in comment.replies"
                  :key="reply.id"
                  class="reply-item"
                >
                  <el-avatar :src="reply.avatar" size="small" />
                  <div class="reply-content">
                    <div class="reply-header">
                      <span class="username">{{ reply.username }}</span>
                      <span class="reply-time">{{ formatTime(reply.createTime) }}</span>
                    </div>
                    <div class="reply-text">
                      <span class="reply-to">@{{ reply.replyTo }}</span>
                      {{ reply.content }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  <script setup>
  import { useRoute } from 'vue-router'
  import dayjs from 'dayjs'
  import { ref, onMounted, reactive, getCurrentInstance, nextTick } from "vue"
  const { proxy } = getCurrentInstance();
  const route = useRoute()

  // 帖子数据
  const postData = ref({
    id: null,
    title: '',
    content: '',
    tags: [],
    viewCount: 0,
    author: '',
    createTime: null
  })

  // 评论数据
  const commentList = ref([])
  const activeReply = ref(null)
  const replyContent = ref('')

  // 评论表单
  const commentForm = ref({
    content: '',
    parentId: null
  })
  const commentFormRef=ref({});

  // 验证规则
  const commentRules = {
    content: [
      { required: true, message: '评论内容不能为空' },
      { max: 500, message: '评论内容不超过500字' }
    ]
  }

  // 获取帖子详情
  const getPostDetail = async () => {
    const postId = route.params.id;
    let params={
      id:postId,

    }
    const res = await proxy.Request({
      url: '/post/loadPost',
      params:params,
    })
    postData.value = res.data
  }

  // 获取评论列表
  const getComments = async () => {
    const res = await proxy.Request({
      url: '/comment/loadCommentList',
      params: { postId: route.params.id }
    })
    // 将评论转换为嵌套结构
    // commentList.value = transformComments(res.data)
    commentList.value = res.data
}

  // 转换评论结构为嵌套格式
  const transformComments = (comments) => {
    const map = {}
    const roots = []
    comments.forEach(comment => {
      map[comment.id] = { ...comment, replies: [] }
      if (comment.parentId) {
        map[comment.parentId]?.replies.push(map[comment.id])
      } else {
        roots.push(map[comment.id])
      }
    })
    return roots
  }

  // 提交评论
  const submitComment = async () => {
    commentFormRef.value.validate(async (valid) => {
        if(!valid){
            return;
        }
       let result =await proxy.Request({
        url: '/comment/saveComment',
        method: 'post',
        params: {
            ...commentForm.value,
            postId: route.params.id
        }
        })
        if(!result){
            return;
        }
        getComments()
        commentForm.value.content = ''
    })
  }

  // 时间格式化
  const formatTime = (timestamp) => {
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm')
  }


  onMounted(() => {
    getPostDetail()
    getComments()
  })
  </script>

  <style scoped lang="scss">
  .post-detail-container {
    max-width: 800px;
    margin: 20px auto;
    padding: 0 20px;
  }

  .post-main {
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);

    .post-title {
      font-size: 24px;
      margin-bottom: 16px;
    }

    .post-meta {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 20px;
      color: #606266;

      .author {
        font-weight: 500;
      }
    }

    .post-content {
      line-height: 1.8;
      margin-bottom: 20px;
    }

    .post-tags {
      display: flex;
      gap: 8px;
    }
  }

  .comment-section {
    margin-top: 30px;

    .comment-title {
      font-size: 18px;
      margin-bottom: 20px;
    }

    .comment-input {
      margin-bottom: 30px;

      .el-button {
        margin-top: 10px;
      }
    }
  }

  .comment-item {
    display: flex;
    gap: 16px;
    padding: 16px;
    background: #fff;
    border-radius: 6px;
    margin-bottom: 12px;

    &.child-comment {
      margin-left: 40px;
      background: #f8f9fa;
    }

    .comment-content {
      flex: 1;

      .comment-header {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 8px;
        color: #606266;

        .username {
          font-weight: 500;
        }
      }

      .comment-text {
        line-height: 1.6;
      }
    }
  }

  .reply-list {
    margin-top: 12px;
    border-left: 2px solid #eee;
    padding-left: 16px;

    .reply-item {
      display: flex;
      gap: 12px;
      padding: 8px 0;

      .reply-content {
        .reply-header {
          display: flex;
          gap: 8px;
          color: #909399;
          font-size: 0.9em;
        }

        .reply-text {
          color: #606266;

          .reply-to {
            color: #409EFF;
            margin-right: 4px;
          }
        }
      }
    }
  }

  .reply-input {
    margin-top: 12px;

    .reply-buttons {
      margin-top: 8px;
      text-align: right;
    }
  }
  </style>